<?php

namespace app\admin\controller;

use app\models\{AgentArea, Agent as Agents, Region, AgentLog};
use think\Db;
use think\Validate;

class Agent extends Base
{


    public function agentlog()
    {
        $model = new AgentLog();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['id'])) {
            $results = $results->where('user_id', $data['id']);
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        return view(null, [
            'list' => $results
        ]);
    }
    public function index()
    {
        $model = new Agents();
        $data = $this->request->get();
        $results = $model->order('id desc');
        if (!empty($data['title'])) {
            $results = $results->where('accounts|nickname', 'like', '%' . $data['title'] . '%');
        }
        $results = $results->paginate(10, false, ['query' => $this->request->param()]);
        foreach ($results as $result) {
            $result['allincome'] = (new AgentLog())->where(['user_id' => $result['id'], 'type' => [1, 2]])->sum('money') ?? 0;
            $result['allincome'] = $result['allincome'] + $result['allmoney'];
            $result['money'] = $result['money'] + $result['tmoney'];
        }
        return view(null, [
            'list' => $results
        ]);
    }


    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require',
                'accounts' => 'require',
            ], [
                'nickname.require' => '昵称不能为空',
                'accounts.require' => '账号不能为空',
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '商家密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where('accounts', $data['accounts'])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 0, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Agents();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }

    public function agentarea()
    {
        $list = (new AgentArea())->order('id desc');
        $data = $this->request->get();
        if (!empty($data['title'])) {
            $list = $list->where('title', 'like', '%' . $data['title'] . '%');
        }
        $province = (new Region())->where(['level' => 1])->select();
        $city = [];
        $area = [];
        $street = [];
        if (!empty($data['agentid'])) {
            $list = $list->where(['agentid' => $data['agentid']]);
        }
        if (!empty($data['province'])) {
            $city_top = (new Region())->where(['level' => 1, 'area_code' => $data['province']])->value('id') ?? 0;
            $city = (new Region())->where(['level' => 2, 'parent_id' => $city_top])->select();
            $list = $list->where(['province' => $data['province']]);
        }
        if (!empty($data['city'])) {
            $area_top = (new Region())->where(['level' => 2, 'area_code' => $data['city']])->value('id') ?? 0;
            $area = (new Region())->where(['level' => 3, 'parent_id' => $area_top])->select();
            $list = $list->where(['city' => $data['city']]);
        }
        if (!empty($data['area'])) {
            $street_top = (new Region())->where(['level' => 3, 'area_code' => $data['area']])->value('id') ?? 0;
            $street = (new Region())->where(['level' => 4, 'parent_id' => $street_top])->select();
            $list = $list->where(['area' => $data['area']]);
        }
        if (!empty($data['street'])) {
            $list = $list->where(['street' => $data['street']]);
        }
        $list = $list->paginate(10)->each(function ($row) {
            $row['province_list'] = [];
            $row['city_list'] = [];
            $row['area_list'] = [];
            $row['street_list'] = [];
            $row['agent_name'] = (new Agents())->where(['id' => $row['agentid']])->value('nickname') ?? '';
            $row['province_list'] = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->value('name') ?? '';
            $row['city_list'] = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->value('name') ?? '';
            $row['area_list'] = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->value('name') ?? '';
            $row['street_list'] = (new Region())->where(['level' => 4, 'id' => $row['street']])->value('name') ?? '';
            return $row;
        });
        $agent = (new Agents())->field('id,nickname,accounts')->where('status', 1)->select();
        return view(null, [
            'list' => $list,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'street' => $street,
            'agent' => $agent
        ]);
    }

    public function agentarea_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'agentid' => 'require',
                'type' => 'require|in:2,3,4'
            ], [
                'agentid.require' => '服务商家不能为空',
                'type.require' => '类型不能为空',
                'type.in' => '类型不正确'
            ]);
            if (!$validate->check($data)) {
                return json(['status' => 1, 'msg' =>  $validate->getError()]);
            }
            switch ($data['type']) {
                case '2':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => [3, 4], 'city' => $data['city']])->find();
                    if (!empty($havearea)) {
                        return json(['status' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['area'] = 0;
                    $data['street'] = 0;
                    break;
                case '3':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加高级别需要删除低级别权限
                    $havearea = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 4, 'area' => $data['area']])->find();
                    if (!empty($havearea)) {
                        return json(['status' => 1, 'msg' => '添加或更改更高级别区域管理前请先确认并删除低级别区域管理权限']);
                    }
                    $data['street'] = 0;
                    break;
                case '4':
                    if (empty($data['province'])) {
                        return json(['status' => 1, 'msg' => '请选择省份']);
                    }
                    if (empty($data['city'])) {
                        return json(['status' => 1, 'msg' => '请选择城市']);
                    }
                    if (empty($data['area'])) {
                        return json(['status' => 1, 'msg' => '请选择区域']);
                    }
                    if (empty($data['street'])) {
                        return json(['status' => 1, 'msg' => '请选择街道']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 2, 'city' => $data['city']])->find();
                    if (!empty($haveareat)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的城市管理，无需再添加低级别城市管理']);
                    }
                    //添加级别需要查询是否拥有高级别权限
                    $haveareat2 = (new AgentArea())->where(['agentid' => $data['agentid'], 'type' => 3, 'area' => $data['area']])->find();
                    if (!empty($haveareat2)) {
                        return json(['status' => 1, 'msg' => '您已拥有高级别的区域管理，无需再添加低级别区域管理']);
                    }
                    break;
                default:
                    return json(['status' => 1, 'msg' => '代理区域类型错误']);
                    break;
            }
            //查询负责区域是否已存在
            $businessarea = (new AgentArea())->where([
                'type' => $data['type'],
                'province' => $data['province'],
                'city' => $data['city'],
                'area' => $data['area'],
                'street' => $data['street']
            ])->find();
            // if (!empty($data['id'])) {
            //     if (!empty($businessarea) && $data['id'] != $businessarea['id']) {
            //         return json(['status' => 1, 'msg' => '管理区域已添加，请选择编辑']);
            //     }
            //     $res = (new AgentArea())->allowfield(true)->save($data, ['id' => $data['id']]);
            // } else {
            if (!empty($businessarea)) {
                return json(['status' => 1, 'msg' => '管理区域已添加或已分配']);
            }
            $res = (new AgentArea())->allowfield(true)->save($data);
            // }
            if ($res) {
                return json(['status' => 0, 'msg' => '编辑成功']);
            }
            return json(['status' => 0, 'msg' => '编辑失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new AgentArea())->where('id', $id)->find();
            $province = (new Region())->where(['level' => 1])->select();
            $city = [];
            $area = [];
            $street = [];
            $agent = (new Agents())->field('id,nickname,accounts')->where('status', 1)->select();
            if (!empty($row)) {
                $parent = (new Region())->where(['level' => 1, 'area_code' => $row['province']])->find();
                $city = (new Region())->where(['level' => 2, 'parent_id' => $parent['id']])->select();
                $carent = (new Region())->where(['level' => 2, 'area_code' => $row['city']])->find();
                $area = (new Region())->where(['level' => 3, 'parent_id' => $carent['id']])->select();
                $aarent = (new Region())->where(['level' => 3, 'area_code' => $row['area']])->find();
                $street = (new Region())->where(['level' => 4, 'parent_id' => $aarent['id']])->select();
            } else {
                $agentid = $this->request->get('agentid/d', 0);
                if (!empty($agentid)) {
                    $row['agentid'] = $agentid;
                }
            }
            return view('', [
                'row' => $row,
                'province' => $province,
                'city' => $city,
                'area' => $area,
                'street' => $street,
                'agent' => $agent
            ]);
        }
    }


    public function agentarea_del()
    {
        $id = trim(input('id'), ',');
        $model = new AgentArea();
        $res = $model->where(['id' => $id])->delete();
        if ($res) {
            return json(['code' => 0, 'status' => 0, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'status' => 0, 'data' => [], 'msg' => '操作失败，请重试']);
    }
}
